<script setup>
import {onMounted, ref} from 'vue';
import luckysheet from "luckysheet";
import {filterValidSampleAdatas, filterValidSamples, processTableData} from '@/utils/method'
import AnalyesAPI from "@/api/system/analyes.ts";
import {useAnalysetStore} from "@/store/index.ts";
import {getUserInfo} from "@/utils/auth";
import {transformData} from "@/utils/method";
import RequirementB from "@/components/analysisSheetComponents/waterCapacity/tmpl50/index.vue";
import dayjs from "dayjs";
import router from "@/router/index";
import Device from "@/components/analysisSheetComponents/component/Device.vue";
import Index from '@/components/analysisSheetComponents/component/index.vue'

const waterForm = ref({
  pxycd: Array.from({length: 14}, () => ({
    px_ypbh: '',
    px_bod: '',
    px_xdbfpc: '',
    px_zkyq: '',
    px_sfhg: ''
  })),
  kbycd: [
    {kb_ypbh: '', kb_cdnd: '', kb_zkyq: '', kb_sfhg: ''},
    {kb_ypbh: '', kb_cdnd: '', kb_zkyq: '', kb_sfhg: ''},
    {kb_ypbh: '', kb_cdnd: '', kb_zkyq: '', kb_sfhg: ''},
    {kb_ypbh: '', kb_cdnd: '', kb_zkyq: '', kb_sfhg: ''},
    {kb_ypbh: '', kb_cdnd: '', kb_zkyq: '', kb_sfhg: ''},
  ],
  bzycd: [
    {bz_ypbh: '', bz_cdnd: '', bz_bzz: '', bz_sfhg: ''},
    {bz_ypbh: '', bz_cdnd: '', bz_bzz: '', bz_sfhg: ''},
    {bz_ypbh: '', bz_cdnd: '', bz_bzz: '', bz_sfhg: ''},
    {bz_ypbh: '', bz_cdnd: '', bz_bzz: '', bz_sfhg: ''},
    {bz_ypbh: '', bz_cdnd: '', bz_bzz: '', bz_sfhg: ''},
  ],
   // 复制粘贴
    device: {
    device_name: [],
    device_model: [],
    device_number: [],
  }
})
const cdatas = ref([])
const analyseStatusPage = useAnalysetStore()
const record_sn = analyseStatusPage.waterForm.record_sn
const processedData = ref([])
const checkDialogVisible = ref(false)
const checkTime = ref('')
const userInfo = JSON.parse(getUserInfo())

let options = {
  container: "luckysheet", //luckysheet为容器id
  lang: 'zh',
  autoCalculate: true,
  data: [
    {
      "row": 10, // 工作表的下标
      "column": 8, // 列数
      "defaultRowHeight": 40, // 自定义行高
      "defaultColWidth": 100, // 自定义列宽
      "celldata": [
        // 初始化表格数据，第一行包含表头
        {"r": 0, "c": 0, "v": "样品编号",}, // A1
        {"r": 0, "c": 1, "v": "类型",}, // B1
        {"r": 0, "c": 2, "v": "样品COD (mg/L)",}, // B1
        {"r": 0, "c": 3, "v": "接种稀释水或稀释水在培养液中所占比例f1",}, // B1
        {"r": 0, "c": 4, "v": "原样品在培养液中所占比例f2",}, // B1
        {"r": 0, "c": 5, "v": "培养前溶解氧C1 (mg/L)",}, // B1
        {"r": 0, "c": 6, "v": "培养后溶解氧C2 (mg/L)",}, // B1
        {"r": 0, "c": 7, "v": "BOD5(mg/L)",}, // B1
        {"r": 0, "c": 8, "v": "培养方法   1.非稀释法2.非稀释接种法3.稀释法4.稀释接种法",}, // B1
        {"r": 0, "c": 9, "v": "测定结果",}, // B1
        {"r": 0, "c": 10, "v": "备注",}, // B1
      ], // 初始化数据
      "config": {
        "merge": {}, // 合并单元格
        "columnlen": { // 设置列宽
          "0": 130, // 第一列宽度 150px
          "1": 100,
          "2": 130,
          "3": 240,
          "4": 240,
          "5": 240,
          "6": 200,
          "7": 150,
          "8": 260,
          "9": 100,
        }, // 表格列宽
      },
    }
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: true, // 隐藏工具栏
};
const tableOption = ref([
  {table: '仪器名称', id: 1,}
])
const switchAB = ref(true)
const sheetData = ref('')
const jsonData = ref(null)
const switchAdd = ref(true)
// 在组件挂载后初始化 Luckysheet
onMounted(() => {
  // 初始化表格
  luckysheet.create(options);
  // 获取初始数据并保存在响应式变量中
  sheetData.value = options.data
  // 获取表单信息
  getWaterCapacity()
  // 复制粘贴
  getMethod()
});

// 获取信息( 复制粘贴)
const getMethod = () => {
  waterForm.value.task_name = analyseStatusPage.waterForm.task_number //任务名称
  waterForm.value.method = analyseStatusPage.waterForm.tableItem.test_method
      ? analyseStatusPage.waterForm.tableItem.test_method
      : analyseStatusPage.waterForm.tableItem.test_method_number;//分析方法
  waterForm.value.category_id = analyseStatusPage.waterForm.tableItem.sample_category // 样品类别
  checkTime.value = analyseStatusPage.waterForm.tableItemList.submit_dates
}

const handleAddWaterPh = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  console.log(options.data)
  const data = options.data[0].data.map(row => {
    return row
        .map(cell => {
          return cell ? {
            field: cell.m || "默认字段",
            value: cell.v || null
          } : null;
        })
        .filter(cell => cell !== null); // 删除 null 值
  });
  console.log(data);
  // 调用函数
  processedData.value = filterValidSampleAdatas(processTableData(data));
  cdatas.value = filterValidSamples(transformData(processedData.value))
  if (waterForm.value.check_status !== undefined) {
    delete waterForm.value.check_status
    delete waterForm.value.reviewer_id
  }

//   调接口拿数据
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    record_sn: record_sn,
    // record_sn: 50,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
    cdatas: cdatas.value
  }).then(data => {
    console.log('调接口拿数据', data)
    ElMessage.success('保存成功！')
    switchAdd.value = false
  })
};

// 获取——获取 水质容量A   工作表
const getWaterCapacity = () => {
  let josn = {
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    task_id: analyseStatusPage.waterForm.taskId,
    // id: 7,
    record_sn: record_sn,
    // record_sn: 49,
  }
  AnalyesAPI.getAnalyseACapacity(josn).then(data => {
    console.log('获取水质容量 A单', data)
    if (!Array.isArray(data) || data.length !== 0) {
      waterForm.value = data
      sheetData.value = data.configs
      options.data = sheetData.value
      luckysheet.create(options);
      processedData.value = data.adatas
    } else {
      waterForm.value.device = {
        device_name: [],
        device_model: [],
        device_number: [],
      }
    }
  })
}
const handleSwitch = () => {
  switchAB.value = !switchAB.value
}
 
</script>

<template>
  <div class="card">
    <div v-show="switchAB">
      <el-card class="box-card">
        <h1 style="text-align: center">水质 生化需氧量分析原始记录(A面)</h1>
        <div>SXLPHJ/JL/CX-22-50</div>
        <table class="table">
          <tr style="background-color: #f2f2f2">
            <td>任务编号</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.task_name"/>
            </td>
            <td>采样日期</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.sampling_time"/>
            </td>
            <td>分析日期</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.anal_time"/>
            </td>
          </tr>
          <Device :water-form="waterForm"></Device>
          <tr>
            <td>培养箱编号</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.pyxbh"/>
            </td>
            <td>培养温度</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.pywd"/>
            </td>
            <td>培养时间</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.pysj"/>
            </td>
          </tr>
          <tr style="background-color: #f2f2f2">
            <td>环境温度</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.temperature">
                <template #append>
                  <span style="background-color: transparent;color: black">℃</span>
                </template>
              </el-input>
            </td>
            <td>环境湿度</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.humidity">
                <template #append>
                  <span style="background-color: transparent;color: black">%RH</span>
                </template>
              </el-input>
            </td>
            <td>样品类别</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.category_id"/>
            </td>
          </tr>
          <tr>
            <td colspan="2">
              <el-radio-group v-model="waterForm.way">
                <el-radio value="1">碘量法</el-radio>
                <el-radio value="2">电化学探头法</el-radio>
              </el-radio-group>
            </td>
            <td colspan="4">
              <!--              <el-select-->
              <!--                  multiple-->
              <!--                  filterable-->
              <!--                  remote-->
              <!--                  reserve-keyword-->
              <!--                  placeholder="请选择内容"-->
              <!--                  style="width: 100%"-->
              <!--              >-->
              <!--                <el-option-->
              <!--                    v-for="item in tableOption"-->
              <!--                    :key="item.id"-->
              <!--                    :label="item.label"-->
              <!--                    :value="item.id"-->
              <!--                />-->
              <!--              </el-select>-->
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.desc"/>
            </td>
          </tr>
          <tr style="background-color: #f2f2f2">
            <td>样品处理</td>
            <td colspan="5">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.ypcl">
              </el-input>
            </td>
          </tr>
        </table>
        <!--      <input id="uploadBtn" type="file" @change="loadExcel"/>-->
        <div id="luckysheet" style="width:100%;height:500px;"></div>
      </el-card>

    </div>
    <div v-show="!switchAB">
      <requirement-b :water-form="waterForm"></requirement-b>
    </div>
     <!--    底部公共按钮 (复制粘贴)-->
     <div>
      <Index :water-form="waterForm" :handle-add-water-ph="handleAddWaterPh" :check-time="checkTime" :switch="true" :switch-a-b="switchAB" :handle-switch="handleSwitch"
             :get-water-capacity="getWaterCapacity" :switch-add="switchAdd"></Index>
    </div>

    
  </div>

</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse; /* 表格边框合并 */
  text-align: left; /* 默认左对齐 */
  font-size: 14px; /* 字体大小 */
  color: #606266; /* 默认字体颜色 */
  margin-bottom: 20px;
}

.table th,
.table td {
  border: 1px solid #c2bfbf; /* 表格单元格边框颜色 */
  padding: 12px; /* 单元格内边距 */
}

.table th {
  background: #f5f7fa; /* 表头背景色 */
  font-weight: 600; /* 表头字体加粗 */
  color: #303133; /* 表头字体颜色 */
  text-align: center; /* 表头居中 */
}

.table td {
  width: 15%;
}

.table-td {
  display: flex;
}

::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
  flex-direction: row-reverse;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
